#!/usr/bin/make -f

#we need to know the R version
RVERS = $(shell dpkg-query -W --showformat='$${Version}' r-base-core)
RMAJOR = $(shell echo $(RVERS) | awk -F. '{print $$1}')
RMINOR = $(shell echo $(RVERS) | awk -F. '{print $$2}')

# set built-time of GNUR packages to time of created binary package based on stamp in changelog
builttime = $(shell dpkg-parsechangelog -l$(CURDIR)/debian/changelog | awk -F': ' '/Date/ {print $$2}')

# Workaround for cmake not handling CPPFLAGS (https://wiki.debian.org/HardeningWalkthrough):
# As we cannot easily use dh for configuring, we have to merge flags, manually.
CFLAGS += $(CPPFLAGS)
CXXFLAGS += $(CPPFLAGS)

# easier typing
DESTDIR = $(CURDIR)/debian/tmp
BUILDDIR = $(CURDIR)/debian/build

%:
	dh $@ --buildsystem=cmake --builddirectory=$(BUILDDIR)

override_dh_auto_configure:
	mkdir -p $(BUILDDIR)
	# Some installations of R need a specific version of the compiler(s)
	# R CMD config provides info on which compiler to use
	cd $(BUILDDIR) && \
	CC="`/usr/bin/R CMD config CC`" \
	CXX="`/usr/bin/R CMD config CXX`" \
	F77="`/usr/bin/R CMD config F77`" \
	cmake ../.. \
		-DCMAKE_INSTALL_PREFIX=`kde4-config --prefix` \
		-DDATA_INSTALL_DIR=`kde4-config --install data` \
		-DHTML_INSTALL_DIR=`kde4-config --install html` \
		-DKCFG_INSTALL_DIR=`kde4-config --install kcfg` \
		-DINFO_INSTALL_DIR=/usr/share/info \
		-DMAN_INSTALL_DIR=/usr/share/man \
		-DKDE_DEFAULT_HOME=`kde4-config --localprefix` \
		-DCMAKE_SKIP_RPATH=true \
		-DKDE4_USE_ALWAYS_FULL_RPATH=false \
		-DCMAKE_CXX_FLAGS="$(CXXFLAGS)" \
		-DCMAKE_C_FLAGS="$(CFLAGS)" \
		-DCMAKE_EXE_LINKER_FLAGS="$(LDFLAGS)" \
		-DCMAKE_MODULE_LINKER_FLAGS="$(LDFLAGS)" \
		-DCMAKE_SHARED_LINKER_FLAGS="$(LDFLAGS)" \
		-DCMAKE_VERBOSE_MAKEFILE=ON \
		-DKDE4_DISABLE_MULTIMEDIA=ON \
		-DR_EXECUTABLE=/usr/bin/R/ \
		-DR_LIBDIR=/usr/lib/R/site-library/ \
		-DBUILD_TIMESTAMP="$(builttime)"

override_dh_auto_install:
	dh_auto_install

	# dirty hack to get rid of conflicting r.xml file without adjusting all makefiles
	rm -vf $(DESTDIR)/`kde4-config --install data`/katepart/syntax/r.xml
	# remove unneeded R package files
	rm -vf $(DESTDIR)/usr/lib/R/site-library/R.css $(DESTDIR)/usr/lib/R/site-library/rkward/COPYING
	# remove x-test locale
	rm -rvf $(DESTDIR)/usr/share/kde4/apps/rkward/po/x-test $(DESTDIR)/usr/share/locale/x-test

override_dh_compress:
	# do not compress KDE HTML help
	dh_compress -Xusr/share/doc/kde/HTML

override_dh_shlibdeps:
	dh_shlibdeps
	# unfortunately, the r-base-core dependency can not be found by dh_shlibdeps, so we need to get at the version manually
	# NOTE: This "if" is currently always true (see build-deps), but left here, for convenience, in case we get into trouble
	# with binary incompatibility (esp. foward incompatibility) again, in the future.
	@if [ "$(RMAJOR)" -eq "3" ] && [ "$(RMINOR)" -ge "0" ] ; then \
		echo "rvers=r-base-core (>= $(RVERS))" >> $(CURDIR)/debian/rkward.substvars ; \
	fi
